package lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author by 何坤
 * @Classname Chapter02
 * @Description TODO
 * @Date 2019/10/11 14:43
 */
public class Chapter02 {

    public static void main(String[] args) {
        /*long start = System.currentTimeMillis();

        Chapter02 chapter02 = new Chapter02();
        List<Apple> appleList = chapter02.appleList();
        appleList.stream().forEach(System.out::println);
        System.out.println("---------------------------------------");
//        List<Apple> apples = chapter02.filterApples(appleList, new AppleGreenColorPredicate());
        List<Apple> apples = chapter02.filterApples(appleList, (Apple apple) -> "green".equals(apple.getColor()));
        apples.stream().forEach(System.out::println);
        System.out.println("---------------------------------------");
        chapter02.sort(appleList);
        appleList.stream().forEach(System.out::println);
        long end = System.currentTimeMillis();
        System.out.println("程序耗时："+(end - start)+"ms");*/

        List<Apple> apples = new Chapter02().appleList();
        apples.stream().forEach(System.out::println);
        apples.sort((o1, o2) -> o1.getWeight().compareTo(o2.getWeight()));
        System.out.println("----------------------------");
        apples.stream().forEach(System.out::println);


    }

    /**
     * 筛选出颜色为绿色的苹果
     * @param
     * @param apples
     * @return java.util.List<com.hk.chapter02.Apple>
     * @date 2019/10/11 14:54
     * @author 何坤
     */
    public List<Apple> filterApples(List<Apple> apples, ApplePredicate p){
        List<Apple> result = new ArrayList<>();
        for(Apple a : apples){
            if (p.test(a)){
                result.add(a);
            }
        }
        return result;
    }

    public void sort(List<Apple> apples){
        apples.sort((Apple apple1, Apple apple2) -> apple1.getWeight().compareTo(apple2.getWeight()));
    }


    public List<Apple> appleList(){
        return Arrays.asList(
                new Apple("red", 125),
                new Apple("green", 225),
                new Apple("red", 175),
                new Apple("green", 125),
                new Apple("red", 121),
                new Apple("green", 105),
                new Apple("yellow", 155),
                new Apple("red", 185),
                new Apple("red", 122),
                new Apple("green", 149)
        );
    }
}

class AppleComparator implements Comparator<Apple> {

    @Override
    public int compare(Apple o1, Apple o2) {
        return o1.getWeight().compareTo(o2.getWeight());
    }
}
